package ru.papergames.web.blines.battle.network.serverpackets;

import ru.common.network.clientcore.ReceivablePacket;
import ru.papergames.web.blines.battle.network.ClientWebServer;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
//public class CompositeReceivablePacket<T extends MMOClient<?>> extends ReceivablePacket<T> { // TODO: uncomment this line and move this class to core NET
public abstract class CompositeReceivablePacket extends ReceivablePacket<ClientWebServer> {

    @Override
    protected final boolean read() {

        Map<Integer, CompositeBuffer> compositePackets = getClient().getCompositePackets();

        int packetId = readD();
        int packetSize = readD();
        int chunksCount = readH();

        CompositeBuffer compositeBuffer = compositePackets.get(packetId);
        if (compositeBuffer == null) {
            compositeBuffer = new CompositeBuffer(packetId, ByteBuffer.allocate(packetSize).order(ByteOrder.LITTLE_ENDIAN), chunksCount);
            compositePackets.put(packetId, compositeBuffer);
        }
        int curChunkStartPos = readD();
        int curChunkSize = readD();
        byte [] chunk = new byte[curChunkSize];
        readB(chunk);

        compositeBuffer.addChunk(chunk, curChunkStartPos);

        if (!compositeBuffer.isReady()) {
            return false;
        }

        this._buf = compositeBuffer.getBuffer();
        readComposite();
        this._buf = null;
        return true;
    }

    protected abstract void readComposite();

}
